package com.hermit.qmst.UI.activity;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hermit.qmst.R;

import java.util.Iterator;

/**
 * Created by hermithermit on 15/2/18.
 */
public class InviteActivity extends Activity implements View.OnClickListener{

    private EditText metRecomNums;
    private TextView mtvInviteMsg;
    private ImageView mivAddRecom;
    private Button mbtnInvite;
    private boolean mSmsRetFlag = false;
    private String phone;
    private BroadcastReceiver mSmsRet = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (getResultCode()){
                case RESULT_OK:
                        Toast.makeText(InviteActivity.this,"发送成功",Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_invite);
        phone=getIntent().getStringExtra("phone");
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSmsRetFlag){
            unregisterReceiver(mSmsRet);
        }
    }

    private void initView(){

        ((TextView)findViewById(R.id.tv_title)).setText("邀请好友");
        ((ImageView)findViewById(R.id.iv_title_left)).setImageResource(R.drawable.ic_back);
        findViewById(R.id.iv_title_left).setOnClickListener(this);

        metRecomNums = (EditText)findViewById(R.id.recomNums);
        mtvInviteMsg = (TextView)findViewById(R.id.tv_invitemsg);
        mivAddRecom = (ImageView)findViewById(R.id.btnAddReocm);
        mivAddRecom.setOnClickListener(this);

        mbtnInvite = (Button)findViewById(R.id.bt_invite);
        mbtnInvite.setOnClickListener(this);
        String appName=this.getString(R.string.app_name);
        String appDownUrl=this.getString(R.string.app_name_py);
        mtvInviteMsg.setText("hi,我正在使用【"+appName+"】免费打电话,推荐你用一下。下载地址http://120.76.191.63/wap/index.php?agent_name="+appDownUrl);
        metRecomNums.setText(phone);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_title_left:
                InviteActivity.this.finish();
                break;

            case R.id.btnAddReocm:
                //调用手机联系人
                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent,1);
                break;
            case R.id.bt_invite:
                sendSMS();
                break;

            default:
                break;
        }
    }

    private String getPhoneByContactId(String id){
        Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI
                        ,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id,null,null);

        if (cursor.moveToFirst()){
            String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA1));
            cursor.close();
            return phone;
        }

        return null;
    }

    //调用手机联系人返回
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK){
            return;
        }

        if (requestCode == 1){
            String id = data.getData().getLastPathSegment();
            metRecomNums.setText(getPhoneByContactId(id));
        }
    }

    //发送信息
    private void sendSMS(){
        if (metRecomNums.getText().toString().trim().length() == 0){
            Toast.makeText(this,"请输入要推荐的号码",Toast.LENGTH_SHORT).show();
            return;
        }

        SmsManager smsManager = SmsManager.getDefault();
        Intent intent = new Intent("SENT_SMS_ACTION");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,0);

        Intent intent2 = new Intent("DELIVERED_SMS_ACTION");
        PendingIntent pendingIntent2 = PendingIntent.getBroadcast(this,0,intent2,0);

        registerReceiver(mSmsRet,new IntentFilter("SENT_SMS_ACTION"));
        mSmsRetFlag = true;

        Iterator iterator;

        String msg = mtvInviteMsg.getText().toString();
        String nums = metRecomNums.getText().toString();

        if (msg.length() > 70){
            iterator = smsManager.divideMessage(msg).iterator();

            while (true){
                if (!iterator.hasNext()){
                    return;
                }

                Toast.makeText(getBaseContext(),"正在发送...",Toast.LENGTH_SHORT).show();
                smsManager.sendTextMessage(nums,null,(String)iterator.next(),pendingIntent,pendingIntent2);

            }
        }else {
            smsManager.sendTextMessage(nums,null,msg,pendingIntent,pendingIntent2);
        }


    }

    //调用手机发送
    private void sendSMSFromSystem(){
        Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + metRecomNums.getText().toString().trim()));
        intent.putExtra("sms_body",mtvInviteMsg.getText().toString());
        startActivity(intent);
    }
}
